package com.happy.study.controller;

import com.alibaba.fastjson.JSONObject;
import com.happy.study.entity.CategoryEntity;
import com.happy.study.entity.QuestionEntity;
import com.happy.study.entity.UserEntity;
import com.happy.study.servier.IQuestionService;
import com.happy.study.util.ResultBody;
import com.happy.study.util.StateEnum;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Author: Wuzh
 * @Description:
 * @Date Created in 16:18 2021/1/23
 * @return
 */
@Controller
@RequestMapping ("/question")
public class QuestionController {

    @Resource
    private IQuestionService iQuestionService;

    @RequestMapping (value = "/queryList")
    @ResponseBody
    public ResultBody<QuestionEntity> questionList ( String questionEntity ) {
        QuestionEntity question = JSONObject.parseObject ( questionEntity, QuestionEntity.class );
        List<QuestionEntity> questionEntities = iQuestionService.queryList ( question );
        return ResultBody.success ( questionEntities, questionEntities.size () );
    }


    @PostMapping ("/saveQuestion")
    @ResponseBody
    public ResultBody<QuestionEntity> saveQuestion ( QuestionEntity questionEntity, HttpSession session ) {
        UserEntity userEntity = (UserEntity) session.getAttribute ( "userEntity" );
        if ( userEntity == null ) {
            return ResultBody.fail ( StateEnum.REQUEST_POWER_EXCE );
        }
        questionEntity.setUserId ( userEntity.getId () );
        questionEntity = iQuestionService.addSingle ( questionEntity );
        return ResultBody.success ( questionEntity );
    }

    /**
     * 查询一个问题
     *
     * @param id
     * @param model
     * @return
     */
    @GetMapping ("{id}")
    public String querySingle ( @PathVariable int id, Model model ) {
        QuestionEntity questionEntity = iQuestionService.querySingle ( id );
        model.addAttribute ( "questionEntity", questionEntity );
        return "question";
    }
}
